package com.zline.foodraise.ui.activity;

import android.content.ContentValues;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.afollestad.materialdialogs.GravityEnum;
import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.photoselector.model.PhotoModel;
import com.photoselector.ui.PhotoSelectorActivity;
import com.photoselector.util.CommonUtils;
import com.zline.foodraise.R;
import com.zline.foodraise.adapter.ReleaseDynamicPicItemAdapter;
import com.zline.foodraise.constant.Constant;
import com.zline.foodraise.entity.AppPref_;
import com.zline.foodraise.entity.CommentBean;
import com.zline.foodraise.entity.CustomerUserBean;
import com.zline.foodraise.http.HttpDataParsing;
import com.zline.foodraise.http.HttpErro;
import com.zline.foodraise.http.HttpOperator;
import com.zline.foodraise.http.HttpUtil;
import com.zline.foodraise.listener.RecyclerItemClicked;
import com.zline.foodraise.util.EmojiFilter;
import com.zline.foodraise.util.FileUtils;
import com.zline.foodraise.util.ImageUtil;
import com.zline.foodraise.util.LUtil;
import com.zline.foodraise.util.NetworkUtil;
import com.zline.foodraise.util.StringUtils;
import com.zline.foodraise.util.TUtil;
import com.zline.foodraise.view.MyGridLayoutManager;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.AfterTextChange;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by heshantao on 15/7/31.
 * 发布评论
 */
@EActivity(R.layout.activity_release_dynamic)
public class ReleaseCommentActvity extends ZlineActivity
        implements RecyclerItemClicked {
    private static final String LOG_TAG = ReleaseCommentActvity.class.getSimpleName();
    //发表评论
    @StringRes(R.string.add_comment)
    String add_comment_title;
    //回复评论
    @StringRes(R.string.replay_comment)
    String replay_comment_title;
    @ViewById(R.id.app_common_header_title_tv)
    TextView title_tv;
    //评价内容
    @ViewById(R.id.release_dynamic_et)
    EditText comment_content_etv;
    //评价字数
    @ViewById(R.id.release_dynamic_num_tv)
    TextView comment_legth_tv;
    //评论字符数
    int length;
    @ViewById(R.id.release_dynamic_pics_recyclerView)
    RecyclerView picRecyclerview;
    @Bean
    ReleaseDynamicPicItemAdapter adapter;
    SparseArray<String> array;
    @StringRes(R.string.take_new_picture)
    String take_new_pic;
    @StringRes(R.string.chose_from_gallery)
    String chose_from_gallery;
    @StringRes(R.string.replaying_comment)
    String comment_upload_title;
    @StringRes(R.string.releaseing_topic)
    String top_upload_title;
    Intent intent;
    //拍照图片/图库图片uri
    Uri imageUri;
    @Bean
    ImageUtil imageUtil;
    //回复还是添加
    @Extra
    int flag;
    //评论的类型 资源类型：2-项目,3-商品,4-动态
    @Extra
    int resourceType;
    //评论类型的ID
    @Extra
    long resourceId;
    @Extra
    CommentBean commentBean;
    @Extra
    int position;
    @Bean
    HttpOperator httpOperator;
    @Bean
    HttpUtil httpUtil;
    int resultCode = 0;
    @Bean
    HttpErro httpErro;
    @Bean
    HttpDataParsing httpDataParsing;
    //图片上传服务器后的地址列表
    List<String> imageUriList;
    //图片进行压缩后存储后的临时地址
    List<String> temporaryList;
    //图片上传成功返回的服务器地址
    String responseImagePath;
    String uploadPicName;
    //最多支持放多少张图片
    static final int MAX_IMAGE = 5;
    ExecutorService executorService;
    //选择图片的本地地址
    String imagePath;
    //图片上传服务器成功后的存储
    Map<String, String> responsePicMap;
    @Pref
    AppPref_ appPref;
    //评论内容
    String content;
    MaterialDialog uploadDialog;
    @Bean
    NetworkUtil networkUtil;

    @AfterInject
    void doSomeAfterInject() {
        initData();
    }

    void initData() {
        imageUriList = new ArrayList<String>();
        temporaryList = new ArrayList<String>();
        array = new SparseArray<String>();
        responsePicMap = new HashMap<String, String>();
        array.put(0, Constant.DEFAULT_PIC_URI);

    }

    @AfterViews
    void doSomeAfterViews() {
        initView();
    }

    void initView() {
        //提示语
        if (resourceType == 2) {
            comment_content_etv.setHint(R.string.topic_hint);
        } else {
            comment_content_etv.setHint(R.string.comment_hint);
        }

        if (flag == Constant.ADD_COMMENT_FLAG) {//添加
            if (resourceType == 2) {
                title_tv.setText(R.string.release_topic);
            } else {
                title_tv.setText(add_comment_title);
            }
        } else if (flag == Constant.REPLY_COMMENT_FLAG) {//回复
            if (resourceType == 2) {
                title_tv.setText(R.string.replay_topic);
            } else {
                title_tv.setText(replay_comment_title);
            }
        }
        //筹回复不带图片
        setPicRecyclerView();
        if (flag == Constant.REPLY_COMMENT_FLAG && resourceType == 2) {
            picRecyclerview.setVisibility(View.GONE);
        }


    }


    //设置recyclerView
    void setPicRecyclerView() {
        picRecyclerview.setOverScrollMode(RecyclerView.OVER_SCROLL_NEVER);//去除阴影
        MyGridLayoutManager layoutManager = new MyGridLayoutManager(this, 3);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        picRecyclerview.setLayoutManager(layoutManager);
        adapter.setAdapterData(array);
        adapter.setRecycleItemClickListener(this);
        picRecyclerview.setAdapter(adapter);
        picRecyclerview.setItemAnimator(new DefaultItemAnimator());//设置动画
    }

    @AfterTextChange(R.id.release_dynamic_et)
    void textChange() {
        length = comment_content_etv.getText().toString().length();
        comment_legth_tv.setText(length + "/140");
    }


    //选择图片
    void openChosePicDialog() {
        new MaterialDialog.Builder(this)
                .itemsGravity(GravityEnum.CENTER)
                .itemColorRes(R.color.red)
                .items(new String[]{take_new_pic, chose_from_gallery})
                .itemsCallback(new MaterialDialog.ListCallback() {
                    @Override
                    public void onSelection(MaterialDialog materialDialog, View view, int position, CharSequence charSequence) {
                        switch (position) {
                            case 0:
                                takePicFromCamera();
                                break;
                            case 1:
                                takeImageFromFile();
                                break;
                            default:
                                break;
                        }
                    }
                })
                .show();
    }

    //从相机中选择
    void takePicFromCamera() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            /***
             * 需要说明一下，以下操作使用照相机拍照，拍照后的图片会存放在相册中的
             * 这里使用的这种方式有一个好处就是获取的图片是拍照后的原图
             * 如果不实用ContentValues存放照片路径的话，拍照后获取的图片为缩略图不清晰
             */
            ContentValues values = new ContentValues();
            imageUri = this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageUri);
            startActivityForResult(intent, Constant.REQUEST_CODE_CAMERA);
        } else {
            TUtil.showShort(this, R.string.SD_card_not_exit);
        }
    }


    //从file中获取图片
    void takeImageFromFile() {
        intent = new Intent();
        intent.setClass(ReleaseCommentActvity.this, PhotoSelectorActivity.class);
        intent.putExtra(PhotoSelectorActivity.KEY_MAX, MAX_IMAGE - adapter.getArrys().size() + 1);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        startActivityForResult(intent, Constant.REQUEST_CODE_FILE);
    }


    @OnActivityResult(Constant.REQUEST_CODE_CAMERA)
    void onResultCamera(int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        imageUtil.roateBitmap(imageUri);
        SparseArray<String> array = new SparseArray<>();
        array.put(0, CommonUtils.query(this, imageUri));
        addDynamicPic(array);
    }

    @OnActivityResult(Constant.REQUEST_CODE_FILE)
    void onResultFile(int resultCode, Intent data) {
        if (resultCode != RESULT_OK || data == null) {
            return;
        }
        SparseArray<String> array = new SparseArray<String>();
        if (data.getExtras() != null) {
            List<PhotoModel> photos = (List<PhotoModel>) data.getExtras().getSerializable(Constant.PHOTOS);
            if (photos == null || photos.isEmpty()) {
                //没有选择任何东西
            } else {
                for (int i = 0; i < photos.size(); i++) {
                    array.put(i, photos.get(i).getOriginalPath());
                }
                addDynamicPic(array);
            }
        }
    }

    //添加发布动态图片
    void addDynamicPic(SparseArray<String> imagePathArray) {
        int size = adapter.arrys.size();
        adapter.removeItem(size - 1);
        imagePathArray.put(imagePathArray.size(), Constant.DEFAULT_PIC_URI);
        adapter.addAll(imagePathArray);
    }


    //请求上传图片
    void uploadPic(SparseArray<String> imagePathArray) {
        //缓冲池
        executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < imagePathArray.size() - 1; i++) {
            imagePath = imagePathArray.get(i);
            executorService.execute(new PictureUploadThread(imagePath, i));
        }
        executorService.shutdown();

    }


    //使用多线程批量上传图片
    class PictureUploadThread implements Runnable {
        private String mImagePath;

        public PictureUploadThread(String imagePath, int picIndex) {
            mImagePath = imagePath;
        }

        @Override
        public void run() {
            String path = imageUtil.getDiskFileDir(Constant.TEMP) + "/avatar_" + FileUtils.getFileName(mImagePath);
            if (!FileUtils.isFileExist(path)) {//图片存在就不进行压缩处理
                imageUtil.compressImageByPixel(mImagePath, path);
                temporaryList.add(path);
            }
            httpOperator.requestUploadPic(httpUtil, path, requestUploadPicHandler);
        }
    }


    //上传图片回调
    AsyncHttpResponseHandler requestUploadPicHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs_____requestUploadPicHandler_____" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        responseImagePath = response.getString(Constant.URL);
                        uploadPicName = response.getString(Constant.PICTURE_SUFFIX);
                        responsePicMap.put(uploadPicName, responseImagePath);
                        uploadPicAndComment();
                    } else {
                        executorService.shutdownNow();
                        dismissDialog();
                        httpErro.showCommonErroResult(resultCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            dismissDialog();
            executorService.shutdownNow();
        }
    };


    //添加评论
    void addComment() {
        content = comment_content_etv.getText().toString().trim();
        if (StringUtils.isBlank(content)) {
            TUtil.showShort(this, R.string.comment_not_null);
            return;
        } else if (content.length() > 140) {
            TUtil.showShort(this, R.string.over_comment_limite);
            return;
        }
        if (networkUtil.isNetworkAvailable()) {
            openUploadDialog();
            if (adapter.getArrys().size() > 1) {
                uploadPic(adapter.getArrys());
            } else {
                uploadPicAndComment();
            }

        } else {
            TUtil.showShort(this, R.string.no_network);
        }
    }

    //上传图片和评论文字
    synchronized void uploadPicAndComment() {
        LUtil.i(LOG_TAG, "_________上传图文_______");
        long userId = appPref.userId().get();
        Map map = new HashMap();
        if (adapter.getArrys().size() > 1) {
            if (responsePicMap.size() == adapter.getArrys().size() - 1) {
                for (Map.Entry entry : responsePicMap.entrySet()) {
                    String key = (String) entry.getKey();
                    String reponsePicPath = (String) responsePicMap.get(key);
                    imageUriList.add(reponsePicPath);
                }
                map.put(Constant.USER_ID, userId);
                map.put(Constant.RESOURCE_TYPE, resourceType);
                map.put(Constant.RESOURCEID, resourceId);
                map.put(Constant.TAG_CONTENT, content);
                map.put(Constant.PIC_URL_LIST, imageUriList);
                if (commentBean != null) {
                    CustomerUserBean userBean = commentBean.getUserBean();
                    if (userBean == null) return;
                    String reply_name = userBean.getNickName();
                    long reply_id = userBean.getUserId();
                    map.put(Constant.REPLY_USER_ID, reply_id);
                    map.put(Constant.REPLY_NICK_NAME, reply_name);
                }
                Gson gson = new Gson();
                String requestInfo = gson.toJson(map);
                httpOperator.requestAddComment(httpUtil, requestInfo, requestCommentHandler);
            }
        } else {
            map.put(Constant.USER_ID, userId);
            map.put(Constant.RESOURCE_TYPE, resourceType);
            map.put(Constant.RESOURCEID, resourceId);
            map.put(Constant.TAG_CONTENT, content);
            map.put(Constant.PIC_URL_LIST, imageUriList);
            Gson gson = new Gson();
            String requestInfo = gson.toJson(map);
            httpOperator.requestAddComment(httpUtil, requestInfo, requestCommentHandler);
        }

    }

    //回复评论
    void replayComment() {
        content = comment_content_etv.getText().toString().trim();
        if (StringUtils.isBlank(content)) {
            TUtil.showShort(this, R.string.comment_not_null);
            return;
        } else if (content.length() > 140) {
            TUtil.showShort(this, R.string.over_comment_limite);
            return;
        }
        long userId = appPref.userId().get();
        if (adapter.getArrys().size() > 1) {//带图片的回复
            uploadPic(adapter.getArrys());
        } else {//不带图片的回复
            if (commentBean != null) {
                CustomerUserBean userBean = commentBean.getUserBean();
                if (userBean == null) return;
                String reply_name = userBean.getNickName();
                long reply_id = userBean.getUserId();
                openUploadDialog();
                httpOperator.requestReplyComment(httpUtil, userId, resourceType, resourceId
                        , reply_id, reply_name, content, requestCommentHandler
                );
            }
        }

    }


    //添加、回复评论回调
    AsyncHttpResponseHandler requestCommentHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs_____requestCommentHandler_____" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        setCommentResult();
                    } else {
                        httpErro.showCommentErroResult(resultCode);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            dismissDialog();
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            dismissDialog();
        }
    };


    //发布评论后返回
    void setCommentResult() {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putString(Constant.DYNAMIC_COMMENT_CONTENT, content);
        bundle.putInt(Constant.POSITION, position);
        intent.putExtras(bundle);
        this.setResult(Constant.COMMENT_RESULT_CODE, intent);
        finish();
    }


    //回复、发布评论上传服务器时候显示的对话框
    void openUploadDialog() {
        String title = null;
        if (resourceType == 2) {
            title = top_upload_title;
        } else {
            title = comment_upload_title;
        }
        uploadDialog = new MaterialDialog.Builder(this)
                .title(title)
                .titleGravity(GravityEnum.CENTER)
                .content(R.string.upload_Pic_content)
                .progress(true, 0)
                .autoDismiss(false)
                .widgetColorRes(R.color.red)
                .progressIndeterminateStyle(true)
                .show();
        uploadDialog.setCanceledOnTouchOutside(false);//点击dialog 外面不消失
    }

    //关闭对话框
    void dismissDialog() {
        if (uploadDialog != null && uploadDialog.isShowing()) {
            uploadDialog.dismiss();
        }
    }


    @Click({R.id.app_common_header_left_icon_iv, R.id.release_dynamic_bottom_rl})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.app_common_header_left_icon_iv:
                goback();
                break;
            case R.id.release_dynamic_bottom_rl:
                if (flag == Constant.ADD_COMMENT_FLAG) {
                    addComment();
                } else if (flag == Constant.REPLY_COMMENT_FLAG) {
                    replayComment();
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onRecyclerItemClicked(int position) {
        //点击+才会添加图片
        if (position == adapter.arrys.size() - 1) {
            if (position == MAX_IMAGE) {//发布动态时候最多添加5张图片
                TUtil.showShort(this, R.string.can_not_add_pic);
                return;
            }
            openChosePicDialog();
        }

    }

    @Override
    public void onRecyclerItemClicked(int flag, int position) {

    }

    @Override
    public void onRecyclerItemClicked(int flag, int position, int parent) {

    }

    @Override
    public void onRecyclerClickedDelete(int position) {//删除临时存储的原图
        String deletPicName = "avatar_" + FileUtils.getFileName(adapter.arrys.get(position));
        if (responsePicMap.containsKey(deletPicName)) {
            responsePicMap.remove(deletPicName);
        }
        adapter.removeFromMiddleItem(position);


    }

    //删除临时图片文件
    @Background
    void delectTemporaryPic() {
        for (int i = 0; i < temporaryList.size(); i++) {
            String path = temporaryList.get(i);
            if (FileUtils.isFileExist(path)) {
                FileUtils.deleteFile(path);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        delectTemporaryPic();
    }
}
